// ShiftOp
// Copyright (c) 1998-2003 Matthew Faupel
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Library Public License for more details.
//
// You should have received a copy of the GNU Library Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// 
// This Java class is inspired in part by the GAGS C++ library which I
// presume to be copyright J. J. Merelo <jmerelo@kal-el.ugr.es>.

package com.micropraxis.gajit;

/**
 * A class that represents a unary genetic operator that randomly adds or
 * subtracts one from the value of a random gene in a chromosome and does the
 * opposite to the next gene in the chromosome.
 * 
 * @author gajit@micropraxis.com
 * @version 0.2
 */
public class ShiftOp extends GenOp
{

	public ShiftOp()
	{
		super(false);
	}

	public Chrom apply(Chrom chrom1)
	{
		return applyAt(selectGene(chrom1), chrom1);
	}

	public Chrom applyAt(int index, Chrom chrom1)
	{
		int numGenes = chrom1.size();

		Integer value1;

		Integer indexadd, index2add;

		if (Math.random() < 0.5)
		{
			indexadd = 1;
			index2add = -1;
		}
		else
		{
			indexadd = -1;
			index2add = 1;
		}

		// Needs at least two genes

		if (numGenes > 1)
		{
			for (int i = 0; i < chrom1.get(index).size(); i++)
			{
				value1 = chrom1.get(index).get(i);
				value1 = (value1 + indexadd) % 12;
				chrom1.get(index).set(i, value1);
			}

			for (int i = 0; i < chrom1.get(index + 1).size(); i++)
			{
				value1 = chrom1.get(index + 1).get(i);
				value1 = (value1 + index2add) % 12;
				chrom1.get(index + 1).set(i, value1);
			}
		}

		return chrom1;
	}

	public Chrom applyAt(int index, Chrom chrom1, Chrom chrom2)
	{
		return applyAt(index, chrom1);
	}
}
